<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="学号" prop="studentId">
        <el-input
          v-model="queryParams.studentId"
          placeholder="请输入学号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="姓名" prop="stuName">
        <el-input
          v-model="queryParams.stuName"
          placeholder="请输入姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="年级" prop="stuGrade">
        <el-select v-model="queryParams.stuGrade" placeholder="请输入年级" clearable @keyup.enter="handleQuery" style="width: 200px">
          <el-option label="大一" value="大一"/>
          <el-option label="大二" value="大二"/>
          <el-option label="大三" value="大三"/>
          <el-option label="大四" value="大四"/>
        </el-select>
      </el-form-item>
      <el-form-item label="卓越班" prop="classID">
        <el-select v-model="queryParams.classID" placeholder="请选择卓越班班级名称"
                   style="width: 200px" clearable @keyup.enter="handleQuery">
          <el-option v-for="item in classinfoList" :key="item.id" :label="item.className" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="classList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="姓名" align="center" prop="stuName" width="100"/>
      <el-table-column label="学号" align="center" prop="studentId" />
      <el-table-column label="卓越班" align="center" prop="classID">
        <template #default="scope">
          <span>{{ CheekClass(scope.row) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="性别" align="center" prop="stuSex" width="75"/>
      <el-table-column label="班级" align="center" prop="stuClass" />
      <el-table-column label="年级" align="center" prop="stuGrade" width="75"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
      v-model:current-page="queryParams.pageNum"
      v-model:page-size="queryParams.pageSize"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      :page-sizes="[10, 20, 30, 40]"
      @size-change="getList"
      @current-change="getList"
      class="custom-pagination"
    />

    <!-- 添加或修改学生信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="classRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="姓名" prop="stuName">
          <el-input v-model="form.stuName" placeholder="请输入姓名" style="width: 400px"/>
        </el-form-item>
        <el-form-item label="学号" prop="studentId">
          <el-input v-model="form.studentId" placeholder="请输入学号" style="width: 400px"/>
        </el-form-item>
        <el-form-item label="卓越班" prop="classID">
          <el-select v-model="form.classID" placeholder="请选择卓越班班级名称"
                     style="width: 400px" clearable @keyup.enter="handleQuery">
            <el-option v-for="item in classinfoList" :key="item.id" :label="item.className" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="性别" prop="stuSex">
          <el-select v-model="form.stuSex" placeholder="请选择性别" style="width: 400px" clearable @keyup.enter="handleQuery">
            <el-option label="男" value="男"/>
            <el-option label="女" value="女"/>
          </el-select>
        </el-form-item>
        <el-form-item label="学院" prop="stuDepartment">
          <el-select v-model="form.stuDepartment" placeholder="请输入学院" style="width: 400px" @visible-change="visibleChange">
            <el-option label="计算机科学与工程学院" value="计算机科学与工程学院" />
            <el-option label="电子科学与工程学院" value="电子科学与工程学院" />
            <el-option label="国际商学院" value="国际商学院" />
            <el-option label="管理学院" value="管理学院" />
            <el-option label="艺术学院" value="艺术学院" />
          </el-select>
        </el-form-item>
        <el-form-item label="班级" prop="stuClass">
          <el-input v-model="form.stuClass" placeholder="请输入班级" style="width: 400px"/>
        </el-form-item>
        <el-form-item label="专业" prop="stuSpeciality">
          <el-select v-model="form.stuSpeciality" placeholder="请输入专业" style="width: 400px">
            <el-option
              v-for="item in stuSpeciality"
              :key="item.value"
              :label="item.value"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="年级" prop="stuGrade">
          <el-select v-model="form.stuGrade" placeholder="请选择年级" style="width: 400px" clearable>
            <el-option label="大一" value="大一"/>
            <el-option label="大二" value="大二"/>
            <el-option label="大三" value="大三"/>
            <el-option label="大四" value="大四"/>
          </el-select>
        </el-form-item>
        <el-form-item label="手机号" prop="stuPhone">
          <el-input v-model="form.stuPhone" placeholder="请输入手机号" style="width: 400px"/>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" style="width: 400px"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Class" lang="ts">
import { listClass, getClass, delClass, addClass, updateClass, exportClass } from '@/apis/system/classMembers'
import { ref, reactive, toRefs, getCurrentInstance,onMounted} from "vue";
import { ElMessage, ElMessageBox } from 'element-plus'
import { listClassinfo } from '@/apis/system/classinfo'

const { proxy } = getCurrentInstance() as { proxy: any}

const classList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<number[]>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {
    id: null,
    studentId: null,
    email: null,
    classID: null,
    stuName: null,
    stuSex: null,
    stuDepartment: null,
    stuClass: '',
    stuSpeciality: null,
    stuGrade: null,
    stuPhone: null,
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    studentId: null,
    email: null,
    classID: null,
    stuName: null,
    stuSex: null,
    stuDepartment: null,
    stuClass: null,
    stuSpeciality: null,
    stuGrade: null,
    stuPhone: null,
  },
  rules: {
    studentId: [
      { required: true, message: "学号不能为空", trigger: "blur" }
    ],
    classID: [
      { required: true, message: "所在卓越班班级名称不能为空", trigger: "blur" }
    ],
    stuName: [
      { required: true, message: "姓名不能为空", trigger: "blur" }
    ],
  }
});
const classinfoList = ref< any[]>([]);
const ClassinfoqueryParams= ref({
  pageNum: 1,
  pageSize: 100000000,
})
const { queryParams, form, rules } = toRefs(data);
const stuSpecialityList = ref([
  {
    stuDepartment: '计算机科学与工程学院',
    stuSpeciality: [
      { value: '软件工程' },
      { value: '网络工程' },
      { value: '物联网工程' },
      { value: '数据科学与大数据技术' },
      { value: '区块链工程' },
      { value: '计算机网络技术' },
      { value: '软件技术' }
    ]
  },
  {
    stuDepartment: '电子科学与工程学院',
    stuSpeciality: [
      { value: '电子信息工程' },
      { value: '自动化' },
      { value: '通信工程' },
      { value: '人工智能' },
      { value: '电子信息工程技术' },
      { value: '电气自动化技术' }
    ]
  },
  {
    stuDepartment: '国际商学院',
    stuSpeciality: [
      { value: '电子商务' },
      { value: '金融工程' },
      { value: '国际经济与贸易' },
      { value: '互联网金融' },
      { value: '商务英语' },
      { value: '物流管理' }
    ]
  },
  {
    stuDepartment: '管理学院',
    stuSpeciality: [
      { value: '财务管理' },
      { value: '会计学' },
      { value: '工程造价' },
      { value: '工程管理' },
      { value: '旅游管理（本）' },
      { value: '旅游管理（专）' },
      { value: '大数据与财务管理' },
      { value: '大数据与会计' }
    ]
  },
  {
    stuDepartment: '艺术学院',
    stuSpeciality: [
      { value: '环境设计' },
      { value: '视觉传达设计' },
      { value: '音乐表演（本）' },
      { value: '音乐表演（专）' },
      { value: '播音与主持（本）' },
      { value: '播音与主持艺术（专）' },
      { value: '舞蹈表演（本）' },
      { value: '舞蹈表演（专）' },
      { value: '数字媒体技术' },
      { value: '艺术设计' }
    ]
  }
])
const stuSpeciality = ref([{ value: '' }])
const visibleChange = (visible: boolean) => {
  for (let i = 0; i < stuSpecialityList.value.length; i++) {
    if (form.value.stuDepartment === stuSpecialityList.value[i].stuDepartment) {
      stuSpeciality.value = stuSpecialityList.value[i].stuSpeciality
      form.value.stuSpeciality=null
    }
  }
};
listClassinfo(ClassinfoqueryParams.value).then(response => {
  if(response.data.code === 200){
    classinfoList.value = response.data.data.records;
    total.value = response.data.data.total;
  }else {
    ElMessage({ message: response.data.msg, type: 'error' });
  }
});

function CheekClass(row:any) {
  for(let i=0;i<classinfoList.value.length;i++){
    if(row.classID===classinfoList.value[i].id){
      return classinfoList.value[i].className
    }
  }
}

/** 查询班级信息列表 */
function getList() {
  loading.value = true;
  listClass(queryParams.value).then(response => {
    if (response.data.code === 200){
      classList.value = response.data.data.records;
      total.value = response.data.data.total;
    }else {
      ElMessage({
        message: response.data.msg,
        type: 'error'
      });
    }
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    studentId: null,
    email: null,
    classID: null,
    stuName: null,
    stuSex: null,
    stuDepartment: null,
    stuClass: '',
    stuSpeciality: null,
    stuGrade: null,
    stuPhone: null,
  };
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    studentId: null,
    email: null,
    classID: null,
    stuName: null,
    stuSex: null,
    stuDepartment: null,
    stuClass: null,
    stuSpeciality: null,
    stuGrade: null,
    stuPhone: null,
  }
  handleQuery();
}
// 多选框选中数据
function handleSelectionChange(selection: any[]) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加学生信息";
}

/** 修改按钮操作 */
function handleUpdate(row: any) {
  reset();
  const _id = row.id || ids.value
  getClass(_id).then(response => {
    if(response.data.code===200){
      form.value = response.data.data;
      open.value = true;
      title.value = "修改学生信息";
      for (let i = 0; i < stuSpecialityList.value.length; i++) {
        if (form.value.stuDepartment === stuSpecialityList.value[i].stuDepartment) {
          stuSpeciality.value = stuSpecialityList.value[i].stuSpeciality
        }
      }
    }
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["classRef"].validate((valid: boolean) => {
  if (valid) {
    if (form.value.id != null) {
      updateClass(form.value).then(response => {
        if(response.data.code === 200){
          ElMessage({ type: 'success', message: '更新成功' })
        }else {
          ElMessage({ type: 'error', message: response.data.msg })
        }
        open.value = false;
        getList();
      });
    } else {
      addClass(form.value).then(response => {
        if(response.data.code === 200){
          ElMessage({ type: 'success', message: '添加成功' })
        }else {
          ElMessage({ type: 'error', message: response.data.msg })
        }
        open.value = false;
        getList();
      });
    }
  }
});

}

/** 删除按钮操作 */
function handleDelete(row: any) {
  const _ids = row.id || ids.value;
  ElMessageBox.alert('是否确认删除？', '提示', {
    confirmButtonText: '确定',
    callback: (action: string) => {
      if (action === 'confirm') {
        delClass(_ids).then(response => {
          if(response.data.code === 200){
            ElMessage({ type: 'success', message: '删除成功' })
          }else{
            ElMessage({ type: 'error', message: response.data.msg })
          }
          getList();
        })
      }
    }
  });
}

// 时间格式化
function formatDateToYYYYMMDDHHMMSS(timestamp: number): string {
  const date = new Date(timestamp);

  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

/** 导出按钮操作 */
function handleExport() {
  const size = queryParams.value.pageSize;
  queryParams.value.pageSize = Number(1e9);
  exportClass(queryParams.value).then(
    res => {
      const link = document.createElement('a');
      try {
        let blob = res.data;
        let _fileName = formatDateToYYYYMMDDHHMMSS(Date.now()) + '.xlsx';
        link.style.display = 'none';
        const url = window.URL.createObjectURL(blob);
        link.href = url;
        link.download = _fileName;
        link.click();
        window.URL.revokeObjectURL(url);
        //显示弹窗，提示正在导出，请稍等
        ElMessage({ type: 'success', message: '正在导出，请稍等' })
      } catch (e) {
        console.log('下载的文件出错', e);
      }
    }
  );
  queryParams.value.pageSize=size;
}


getList();
</script>

<style scoped>
.custom-pagination {
  margin-top: 20px; /* 调整分页组件与表格的间距 */
  display: flex;
  justify-content: center; /* 居中对齐分页组件 */
}

.custom-pagination .el-pagination__total,
.custom-pagination .el-pagination__sizes,
.custom-pagination .el-pager li,
.custom-pagination .btn-prev,
.custom-pagination .btn-next,
.custom-pagination .el-pagination__jump {
  font-size: 14px; /* 调整字体大小 */
  color: #333; /* 调整文字颜色 */
}

.custom-pagination .el-pagination__sizes .el-input .el-input__inner {
  height: 30px; /* 调整输入框高度 */
  line-height: 30px; /* 调整输入框行高 */
}

.custom-pagination .el-pager li {
  min-width: 30px; /* 调整分页按钮最小宽度 */
  height: 30px; /* 调整分页按钮高度 */
  line-height: 30px; /* 调整分页按钮行高 */
  background-color: #f5f7fa; /* 调整分页按钮背景颜色 */
  border-radius: 4px; /* 调整分页按钮圆角 */
  margin: 0 5px; /* 调整分页按钮间距 */
}

.custom-pagination .el-pager li.active {
  background-color: #409eff; /* 调整激活分页按钮背景颜色 */
  color: #fff; /* 调整激活分页按钮文字颜色 */
}

.custom-pagination .btn-prev,
.custom-pagination .btn-next {
  height: 30px; /* 调整前后按钮高度 */
  line-height: 30px; /* 调整前后按钮行高 */
  background-color: #f5f7fa; /* 调整前后按钮背景颜色 */
  border-radius: 4px; /* 调整前后按钮圆角 */
  margin: 0 5px; /* 调整前后按钮间距 */
}

.custom-pagination .btn-prev:hover,
.custom-pagination .btn-next:hover {
  background-color: #409eff; /* 调整前后按钮悬停背景颜色 */
  color: #fff; /* 调整前后按钮悬停文字颜色 */
}
</style>
